package cn.web.lxxf.servlet;

import cn.web.lxxf.JdbcUtils;
import org.apache.commons.lang3.RandomStringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@WebServlet(urlPatterns = "/good/lxxfsave")
@MultipartConfig(
        //上传的文件保存的具体位置
        location = "F:\\upload-image",
        //最大支持的文件上限（单位：字节）
        maxFileSize = 100*1024*1024,
        //最大支持的请求上限（单位：字节），要求：maxRequestSize >= maxFileSize
        maxRequestSize = 104857600
)
public class GoodsSaveServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String name = req.getParameter("n");
        String price = req.getParameter("p");
        Part image = req.getPart("i");
        String fileName = image.getSubmittedFileName();
        String[] strings = fileName.split("\\.");
        String suffix = strings[1];
        String newname = RandomStringUtils.randomAlphabetic(10) + "." + suffix;
        image.write(newname);

        String id = req.getParameter("id");
        if(id != null && !"null".equals(id)){
            String sql = "UPDATE `goods` SET `name` = ? , price = ? , image = ?  WHERE id = ?";
            JdbcUtils.modify(sql,name,price,newname,id);
        }else{
            String sql = "INSERT INTO `goods` (`name`,price,image) VALUES(?,?,?)";
            JdbcUtils.modify(sql,name,price,newname);
        }

        resp.sendRedirect("/lxxf/goods-list.jsp");
    }
}
